﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using WebUI.Models;
using WebUI.Helper;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;

namespace WebUI.Controllers
{
    public class AccountController : Controller
    {
        private static JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();

        //
        // GET: /UserInfo/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 分页加载信息
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">页大小</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort"></param>
        /// <returns>用户信息</returns>
        public JsonResult LoadAllByPage(int page, int start, int limit)
        {
            int total = 0;

            List<Object> list = new List<Object>(limit);

            //分页获取所有用户
            foreach (MembershipUser user in Membership.GetAllUsers(page - 1, limit, out total))
            {
                string[] roles = Roles.GetRolesForUser(user.UserName);
                list.Add(new
                {
                    UserName = user.UserName,
                    Email = user.Email,
                    Roles = roles,
                    CreationDate = user.CreationDate.ToString("yyyy-MM-dd hh:mm:ss"),
                    LastLoginDate = user.LastLoginDate.ToString("yyyy-MM-dd hh:mm:ss"),
                    IsApproved = user.IsApproved
                });
            }

            var resoult = new { success = true, total = total, msg = "", data = list };

            return Json(resoult, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 增加操作员
        /// </summary>
        /// <returns>操作员</returns>
        [HttpPost]
        public JsonResult Add()
        {
            //获取数据
            string data = Request["data"] ?? "";

            bool success = false;
            String msg = "";
            AccountModel model = null;

            if (string.IsNullOrEmpty(data))
            {
                msg = "错误的交互数据!";
            }
            else
            {
                try
                {
                    model = javascriptSerializer.Deserialize<AccountModel>(data);

                    MembershipCreateStatus status;
                    MembershipUser user = Membership.CreateUser(model.UserName, "123456", model.Email, null, null, model.IsApproved, out status);
                    if (status == MembershipCreateStatus.Success)
                    {
                        //给用户分配角色
                        Roles.AddUserToRoles(model.UserName, model.Roles);

                        success = true;
                    }
                    else
                    {
                        msg = "创建用户失败!";
                    }
                }
                catch (Exception e)
                {

                    msg = e.Message;
                }
            }
            return Json(new { success = success, total = 0, Msg = msg, data = model });
        }

        /// <summary>
        /// 编辑操作员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Edit()
        {
            string data = Request["data"] ?? "";
            bool success = false;
            string Msg = "";
            int total = 0;

            AccountModel model = null;

            if (string.IsNullOrEmpty(data))
                Msg = "服务器没有获取提交的数据";
            else
            {
                Edit(data, ref success, ref Msg, ref model);
            }
            return Json(new { success = success, total = total, Msg = Msg, data = model });
        }

        //编辑操作员
        private static void Edit(string data, ref bool success, ref string Msg, ref AccountModel model)
        {
            try
            {
                model = javascriptSerializer.Deserialize<AccountModel>(data);
                MembershipUser user = Membership.GetUser(model.UserName);
                string[] oRoles = Roles.GetRolesForUser(user.UserName);
                if (user != null)
                    success = Edit(success, model, user);
                else
                {
                    Msg = "用户不存在!";
                }


                Membership.UpdateUser(user);
            }
            catch (Exception e)
            {

                Msg = e.Message;
            }
        }

        //编辑操作员
        private static bool Edit(bool success, AccountModel model, MembershipUser user)
        {
            user.Email = model.Email;
            user.IsApproved = model.IsApproved;
            //现在的角色
            string[] nRoles = model.Roles;
            //原有角色
            string[] oRoles = Roles.GetRolesForUser(model.UserName);
            //全部角色
            string[] aRoles = Roles.GetAllRoles();

            //比较角色
            foreach (string r in aRoles)
            {
                //新角色不在原有角色
                if (nRoles.Contains(r))
                {
                    if (!oRoles.Contains(r))
                    {
                        Roles.AddUserToRole(user.UserName, r);
                    }
                }
                else
                {
                    //角色移除
                    if (oRoles.Contains(r))
                    {
                        Roles.RemoveUserFromRole(user.UserName, r);
                    }
                }
            }
            success = true;
            return success;
        }

        /// <summary>
        /// 删除操作员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles="系统管理员")]
        public JsonResult Removes()
        {
            bool success = false;
            int total = 0;
            string msg = "";
            List<AccountModel> model = null;

            string data = Request["data"] ?? "";
            if (string.IsNullOrEmpty(data))
                msg = "数据格式错误";
            else
            {
                try
                {
                    model = javascriptSerializer.Deserialize<List<AccountModel>>(data);
                    foreach (AccountModel acount in model)
                    {
                        Membership.DeleteUser(acount.UserName);
                    }
                    success = true;
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
            }
            return Json(new { success = success, total = total, Msg = msg, data = model });
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "系统管理员")]
        public JsonResult ResetPassword()
        {
            bool success = false;
            string msg = "";
            string data = Request["id"] ?? "";
            if (string.IsNullOrEmpty(data))
            {
                msg = "没有选择数据!";
            }
            else
            {
                try
                {
                    string[] idlist = data.Split(new char[] { ',' });
                    foreach (string s in idlist)
                    {
                        //Guid g = new Guid(s);
                        MembershipUser user = Membership.GetUser(s);
                        if (user != null)
                        {
                            String opd = user.ResetPassword();
                            user.ChangePassword(opd, "123123");
                        }
                        else
                        {
                            msg = "没有找到对应的用户!";
                        }
                        success = true;
                    }
                }
                catch (Exception e)
                {

                    msg = e.Message;
                }

            }

            return Json(new { success = success, Msg = msg });
        }

        /// <summary>
        /// 新增或者编辑视图
        /// </summary>
        /// <param name="id">用户编码</param>
        /// <returns>用户视图</returns>
        public ActionResult UserView(int? id)
        {
            return View();
        }

        /// <summary>
        /// 判断登录名称是否存在
        /// </summary>
        /// <param name="account">登录名称</param>
        /// <returns>是否存在状态</returns>
        public JsonResult Exists(string account)
        {
            return Json("Extjs");
        }

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <returns></returns>
        public JsonResult Save(string userInfo)
        {
            return Json("json");
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="list">多行用户信息</param>
        /// <returns>删除状态</returns>
        public JsonResult Del(string[] list)
        {
            return Json("publ");
        }

        /// <summary>
        /// 处理登录的Action
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns>登录状态</returns>
        [HttpPost]
        public JsonResult DoLogOn(LogonModel model)
        {
            bool success = false;

            //如果前台验证通过了
            if (ModelState.IsValid)
            {
                //判断验证码
                //string vcode = "";
                //if (Session["vcode"] != null)
                //    vcode = Session["vcode"].ToString();
                //if (vcode.Length > 0 && vcode.ToLower() == model.Vcode)
                //{
                    MembershipUser user = Membership.GetUser(model.UserName);

                    //验证用户是否存在
                    if (user != null)
                    {
                        //用户是否被禁用
                        if (user.IsApproved)
                        {
                            TimeSpan ts = user.LastLockoutDate.AddMilliseconds(60) - DateTime.Now;

                            //用户是否被锁定
                            if (!user.IsLockedOut && ts.Minutes <= 0)
                            {
                                //如果被锁者解锁
                                if (user.IsLockedOut)
                                    user.UnlockUser();
                                //验证用户名密码是否正确
                                if (Membership.ValidateUser(user.UserName, model.Password))
                                {
                                    //验证角色是否符合后台要求
                                    if (Roles.IsUserInRole(model.UserName, "系统管理员") || Roles.IsUserInRole(model.UserName, "普通用户"))
                                    {
                                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                                        return Json(new
                                        {
                                            success = true
                                        });
                                    }
                                    else
                                    {
                                        return Json(new
                                        {
                                            success = false,
                                            error = "没有权限!"
                                        });
                                    }
                                }
                                else
                                {
                                    return Json(new
                                    {
                                        success = false,
                                        error = "密码错误!"
                                    });
                                }
                            }
                            else
                            {
                                return Json(new
                                {
                                    success = false,
                                    error = "用户被锁定" + ts.Minutes + "分钟!"
                                });
                            }
                        }
                        else
                        {
                            return Json(new
                            {
                                success = false,
                                error = "该用户被禁用!"
                            });
                        }


                    }
                    else
                        return Json(new
                        {
                            success = false,
                            error = "用户不存在!"
                        });
                //}
                //else
                //{
                //    return Json(new
                //    {
                //        success = false,
                //        error = "验证码错误"
                //    });
                //}
            }
            else
            {
                return Json(new
                {
                    success = false
                });
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
